package svc

import (
	"fmt"
	"log"
	"os"
	"server/internal/config"
	"server/internal/middleware"
	"server/utils"
	"time"

	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type ServiceContext struct {
	Config          config.Config
	UserMiddleware  rest.Middleware
	AdminMiddleware rest.Middleware
}

func NewServiceContext(c config.Config) *ServiceContext {
	gormConfig := &gorm.Config{}

	if c.DataConf.ShowSql {
		newLogger := logger.New(
			log.New(os.Stdout, "\r\n", log.LstdFlags),
			logger.Config{
				SlowThreshold: time.Second,
				LogLevel:      logger.Info,
				Colorful:      true,
			},
		)
		gormConfig.Logger = newLogger
	}
	dataSource := fmt.Sprintf("user=%s password=%s host=%s port=%d dbname=%s sslmode=disable TimeZone=Asia/Shanghai", c.DataConf.User, c.DataConf.Pass, c.DataConf.Host, c.DataConf.Port, c.DataConf.Database)
	db, err := gorm.Open(postgres.Open(dataSource), gormConfig)
	if err != nil {
		log.Panic("gorm error :", err)
	}
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: fmt.Sprintf("%s:%d", c.RedisConf.Host, c.RedisConf.Port),
		Type: "node",
		Pass: c.RedisConf.Pass,
	})
	if err != nil {
		log.Panic("redis error :", err)
	}
	utils.Init(db, rds, c)
	return &ServiceContext{
		Config:          c,
		UserMiddleware:  middleware.NewUserMiddleware().Handle,
		AdminMiddleware: middleware.NewAdminMiddleware().Handle,
	}
}
